﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyCircle : EnemyBase
{
    private bool colliderReset;
    Vector2 centerPos;
    float radius;
    float angle;
    float AngleSpeed = 0.5f;
    bool bReverse = false;

    public override void Init(EnemyMode mode, Vector3 spawnPos, FaceDir dir)
    {
        base.Init(mode, spawnPos, dir);

        radius = Random.Range(3.0f, 7.0f);

        float x = spawnPos.x;
        float y = spawnPos.y;

        if (Mathf.Abs(y) + radius < 6)
        {
            if (Random.Range(0,2) == 0) y += radius;
            else y -= radius;
        }
        else
        {
            if ( y >= 0 ) y -= radius;
            else y += radius;
        }
        if ( dir == FaceDir.FACE_DIR_LEFT)
        {
            bReverse = true;
        }
        
        centerPos = new Vector2(x, y);
    }

    protected override void FixedTick(float fixedDeltaTime)
    {
        if (bIsDead)
        {
            return;
        }

        if (colliderReset)
        {
            col2d.enabled = true;
            colliderReset = false;
        }

        float angleTemp = angle + AngleSpeed * fixedDeltaTime;
        //angle += AngleSpeed * fixedDeltaTime;
        
        float x = bReverse ? centerPos.x + Mathf.Cos(angleTemp) * radius : centerPos.x - Mathf.Cos(angleTemp) * radius;
        float y = bReverse ? centerPos.y + Mathf.Sin(angleTemp) * radius : centerPos.y - Mathf.Sin(angleTemp) * radius;

        //超出边界处理
        if (x < EnumBase.playerMinX || x > EnumBase.playerMaxX || y < EnumBase.playerMinY || y > EnumBase.playerMaxY)
        {
            col2d.enabled = false;
            colliderReset = true;
            AngleSpeed = Mathf.Min(AngleSpeed + 0.1f, 5.0f);
            //rb2d.MovePosition(spawnPos);
        }
        else
        {
            AngleSpeed = 0.5f;
        }

        angle += AngleSpeed * fixedDeltaTime;
        x = bReverse ? centerPos.x + Mathf.Cos(angle) * radius : centerPos.x - Mathf.Cos(angle) * radius;
        y = bReverse ? centerPos.y + Mathf.Sin(angle) * radius : centerPos.y - Mathf.Sin(angle) * radius;

        rb2d.MovePosition(new Vector2(x, y));
    }
}
